package com.blog.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.blog.blog.dao.pojo.SysUser;
import com.blog.blog.service.LoginService;
import com.blog.blog.service.SysUserService;
import com.blog.blog.utils.JWTUtil;
import com.blog.blog.utils.RedisKeyUtil;
import com.blog.blog.vo.ErrorCode;
import com.blog.blog.vo.Result;
import com.blog.blog.vo.params.LoginParams;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;


import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    private static final String slat = "mszlu!@#";

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Result login(LoginParams loginParams) {
        /**
         * 1.检查参数是否合法
         * 2.根据用户名和密码去user表中查询是否存在
         * 3.如果不存在 登陆失败
         * 4.如果存在，使用jwt生成token返回给前端
         * 5.token放入redis当中，redis token:user信息 设置过期时间
         * (登录认证时 先认证token字符串是否合法，去redis认证是否存在)
         */
        String account = loginParams.getAccount();
        String password = loginParams.getPassword();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(account)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        //password = DigestUtils.md5Hex(password + slat);
        SysUser user = sysUserService.findUser(account, password);
        if (user == null) {
            return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
        }
        HashMap<String, String> payload = new HashMap<>();
        payload.put("account", user.getAccount());
        payload.put("id", user.getId().toString());
        String token = JWTUtil.getToken(payload);
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(user),7, TimeUnit.DAYS);
        return Result.success(token);
    }

    @Override
    public Result logout(String ticket) {
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        redisTemplate.delete(redisKey);
        SecurityContextHolder.clearContext();
        return Result.success(null);
    }
}
